package com.atdel.demo11;


/**
 * @BelongsProject: java_study
 * @BelongsPackage: com.atdel.demo11
 * @Author: Del
 * @CreateTime: 2025-03-11  19:38
 * @Description: 使用继承线程实现卖票功能
 * @Version: 1.0
 */
public class MovieTicketSaleThread extends Thread{

    //  电影票数，使用volatile确保可见性
    private static volatile int tickets = 50;

    public MovieTicketSaleThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        while (tickets > 0) {
            // 卖票 ---> 涉及到资源共享需要加锁
            synchronized (MovieTicketSaleThread.class) {
                if (tickets <= 0) {
                    System.out.println("票卖完了");
                    break;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets-- + "张票");
            }
        }
    }
}
